package cn.com.duiba.millionaire.center.biz.service.impl;

import cn.com.duiba.millionaire.center.api.constant.RedisKeyFactory;
import cn.com.duiba.millionaire.center.api.msg.SubmitAnswerMsg;
import cn.com.duiba.millionaire.center.biz.service.RenascenceUsageInfoCacheService;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by zzy on 2018/1/24.
 */
@Service
public class RenascenceUsageInfoCacheServiceImpl implements RenascenceUsageInfoCacheService {
    @Resource(name = "redisTemplate")
    private RedisTemplate<String, Long> redisTemplate;

    @Override
    public void batchAdd(List<SubmitAnswerMsg> submitAnswerMsgs) {
        redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                RedisSerializer<Object> keyS = (RedisSerializer<Object>) redisTemplate.getKeySerializer();
                RedisSerializer<Object> valueS = (RedisSerializer<Object>) redisTemplate.getValueSerializer();
                submitAnswerMsgs.stream().forEach(e ->{
                    byte[] redisKey = keyS.serialize(buildKey(e.getActivityId(), e.getQuestionIndex()));
                    redisConnection.sAdd(redisKey, valueS.serialize(e.getConsumerId()));
                    redisConnection.expire(redisKey,3 * 24 * 3600);
                });

                return null;
            }
        });
    }

    @Override
    public Long findCount(Long activityId, Integer questionIndex) {
        return redisTemplate.opsForSet().size(buildKey(activityId,questionIndex));
    }

    private String buildKey(Long activityId, Integer questionIndex) {
        return RedisKeyFactory.K011.toString() + activityId + "_" + questionIndex;
    }
}
